package com.wmh.baseservice.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.pojo.SortWay;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.MerchantActivity;
import com.wmh.baseservice.merchant.pojo.MerchantInfo;
import com.wmh.baseservice.merchant.service.MerchantActivityService;
import com.wmh.baseservice.merchant.service.MerchantInfoService;
import com.wmh.baseservice.user.pojo.UsActivityRegister;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.pojo.vo.ActivityRegisterDetailVO;
import com.wmh.baseservice.user.service.UsActivityRegisterService;
import com.wmh.baseservice.user.service.UsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author wmh generator
 * @since 2022-04-09
 */
@Api(tags = "用户端-活动报名相关接口")
@RestController
@RequestMapping(value = "user/usActivity", produces = "text/plain;charset=utf-8")
public class UsActivityController {

    @Resource
    private UsActivityRegisterService usActivityRegisterService;
    @Resource
    private MerchantActivityService merchantActivityService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private MerchantInfoService merchantInfoService;


    @ApiOperation("判断用户是否报名")
    @PostMapping("isSignUp")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "活动id", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "type", value = "报名方法 0免费 1收费", required = true),
    })
    @ParameterVerify(notNull = {"activityId"})
    public String isSignUp(Long activityId) {
        Long usId = (Long) request.getAttribute("usId");
        boolean result = false;
        UsActivityRegister register = usActivityRegisterService.getOneForUpdate(new QueryWrapper<UsActivityRegister>()
                .eq(UsActivityRegister.ACTIVITY_ID, activityId)
                .eq(UsActivityRegister.US_ID, usId)
                .in(UsActivityRegister.STATUS, 0, 1, 2)
        );
        if (register != null) {
            result = true;
        }
        return ReturnBody.success(result);
    }


    @ApiOperation("活动报名")
    @PostMapping("register")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "活动id", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "type", value = "报名方法 0免费 1收费", required = true),
    })
    @ParameterVerify(notNull = {"id", "method"})
    public String register(Long id, Integer method) {
        Long usId = (Long) request.getAttribute("usId");
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        MerchantActivity merchantActivity = merchantActivityService.getByIdForUpdate(id);
        usActivityRegisterService.register(merchantActivity, usInfo, method, 1);
        return ReturnBody.success();
    }

    @ApiOperation("取消报名")
    @PostMapping("cancelSignUp")
    @ParameterVerify(notNull = "registerId")
    public String cancelSignUp(Long registerId) {
        usActivityRegisterService.cancelSignUp(registerId);
        return ReturnBody.success();
    }

    @ApiOperation("余额支付报名")
    @PostMapping("payBalance")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "活动id", required = true),
    })
    @ParameterVerify(notNull = "id")
    public String payBalance(Long id) {
        Long usId = (Long) request.getAttribute("usId");
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        MerchantActivity merchantActivity = merchantActivityService.getByIdForUpdate(id);
        usActivityRegisterService.payBalance(merchantActivity, usInfo);
        return ReturnBody.success();
    }

    @ApiOperation("微信支付报名")
    @PostMapping("wechatPaySignUp")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "活动id", required = true),
    })
    @ParameterVerify(notNull = "activityId")
    public String wechatPaySignUp(Long activityId) {
        Long usId = (Long) request.getAttribute("usId");
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        MerchantActivity merchantActivity = merchantActivityService.getByIdForUpdate(activityId);
        String orderNum = usActivityRegisterService.register(merchantActivity, usInfo, 1, 0);
        return ReturnBody.success(orderNum);
    }


    @ApiOperation("报名人员")
    @PostMapping("registerPeople")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "活动id", required = true),
    })
    @ParameterVerify(notNull = "id")
    public String registerPeople(Long id) {
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageSize(20);
        pageInfo.setDefaultSort(UsActivityRegister.CREATE_TIME, SortWay.DESC);
        pageInfo.setPageNo(1);
        //执行分页辅助工具
        PageResult<UsActivityRegister> pageResult = new PageUtil<UsActivityRegister>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.eq(UsActivityRegister.ACTIVITY_ID, id);
            queryWrapper.in(UsActivityRegister.STATUS,0,1,2);
            usActivityRegisterService.page(page, queryWrapper);
        });
        pageResult.getList().forEach(item -> {
            UsInfo usInfo = usInfoService.getByIdForUpdate(item.getUsId());
            item.setAvatar(usInfo.getAvatar());
            item.setNick(usInfo.getNick());
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("活动签到")
    @PostMapping("signUp")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "活动id", required = true),
    })
    @ParameterVerify(notNull = "id")
    public String signUp(Long id) {
        Long usId = (Long) request.getAttribute("usId");
        UsActivityRegister usActivityRegister = usActivityRegisterService.getOneForUpdate(
                new QueryWrapper<UsActivityRegister>()
                        .eq(UsActivityRegister.ACTIVITY_ID, id)
                        .eq(UsActivityRegister.US_ID, usId)
                        .in(UsActivityRegister.STATUS, 0, 1, 2)
        );
        if (!CommUtil.checkNull(usActivityRegister)) {
            return ReturnBody.error("您未参加活动");
        }
        if (usActivityRegister.getStatus() == -1) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        usActivityRegister.setStatus(2);
        if (!usActivityRegisterService.updateById(usActivityRegister)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("报名活动列表")
    @PostMapping("list")
    public String list(PageInfo pageInfo, Integer status) {
        Long usId = (Long) request.getAttribute("usId");
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //执行分页辅助工具
        PageResult<UsActivityRegister> pageResult = new PageUtil<UsActivityRegister>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.eq(UsActivityRegister.US_ID, usId);
            if (CommUtil.checkNull(status)) {
                queryWrapper.eq(UsActivityRegister.STATUS, status);
            }
            usActivityRegisterService.page(page, queryWrapper);
        });
        pageResult.getList().forEach(item -> {
            Long merchantId = item.getMerchantId();
            if (merchantId != null) {
                MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(merchantId);
                if (merchantInfo != null) {
                    item.setMerchantName(merchantInfo.getStoreName());
                }
            }
            Long activityId = item.getActivityId();
            if (activityId != null) {
                MerchantActivity activity = merchantActivityService.getByIdForUpdate(activityId);
                if (activity != null) {
                    if (activity.getHasCost() == 1) {
                        item.setCost(activity.getCost());
                    }
                    item.setActivityTitle(activity.getTitle()).setActivityBanner(activity.getBanner());
                    item.setOpenTime(activity.getOpenTime());
                }
            }
        });
        return ReturnBody.success(pageResult);
    }


    @ApiOperation("活动记录详情")
    @PostMapping("detail")
    public String detail(Long registerId) {
        Long usId = (Long) request.getAttribute("usId");
        UsActivityRegister register = usActivityRegisterService.getById(registerId);
        if (register == null) {
            return ReturnBody.error("活动详情丢失,请重试或联系管理员");
        }
        ActivityRegisterDetailVO result = new ActivityRegisterDetailVO();
        result.setRecordId(register.getId().toString())
                .setRegistrationTime(String.valueOf(register.getCreateTime().getTime()))
                .setRegisterStatus(register.getStatus())
                .setOrderNum(register.getOrderNum());
        MerchantActivity activity = merchantActivityService.getById(register.getActivityId());
        if (activity != null) {
            result.setActivityTitle(activity.getTitle()).setActivityOverview(activity.getOverview())
                    .setActivityLat(activity.getLat()).setActivityLng(activity.getLng())
                    .setHasCost(activity.getHasCost()).setCost(activity.getCost())
                    .setActivityBanner(activity.getBanner())
                    .setOpenTime(String.valueOf(activity.getOpenTime().getTime()))
                    .setOverTime(String.valueOf(activity.getOverTime().getTime()))
                    .setActivityId(activity.getId().toString())
                    .setActivityAddress(activity.getAddress());
        }
        MerchantInfo merchantInfo = merchantInfoService.getById(register.getMerchantId());
        if (merchantInfo != null) {
            result.setStoreId(merchantInfo.getId().toString())
                    .setStoreName(merchantInfo.getStoreName())
                    .setStoreAvatar(merchantInfo.getStoreAvatar());
        }
        return ReturnBody.success(result);
    }
}
